package com.example.oauth.authserver.service;

import com.example.oauth.authserver.model.SubjectBO;
import com.example.oauth.authserver.repository.SubjectRepository;
import com.example.oauth.authserver.repository.entity.Resource;
import com.example.oauth.authserver.repository.entity.Role;
import com.example.oauth.authserver.repository.entity.Subject;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>
 *
 * @author chang.zhou
 * @version 1$
 * @date Created in 2022/3/6 0:19
 */
@AllArgsConstructor
@Service
public class SubjectService implements UserDetailsService {
    SubjectRepository repository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        final Subject subject = this.repository.findSubjectByLoginName(username);
        if(subject == null){
            throw new UsernameNotFoundException("no subject found");
        }
        SubjectBO subjectBO = new SubjectBO(subject.getLoginName(),
                subject.getPassword(),
                subject.getAccountNotExpired(),
                subject.getAccountNotLocked(),
                subject.getCredentialsNotExpired(),
                subject.getEnabled());

        List<String> collect = subject.getRoles().stream().map(Role::getRoleCode).collect(Collectors.toList());
        subject.getRoles().forEach(x -> {
            final List<String> collect1 = x.getResources().stream().map(Resource::getUrl).collect(Collectors.toList());
            collect.addAll(collect1);
        });
        subjectBO.setRoles(collect);

        return subjectBO;
    }
}
